using IM.Easy.Infrastructure.Query;
using Microsoft.AspNetCore.Mvc;
using IM.Easy.SystemServices.Dtos;
using IM.Easy.SystemServices.IServices;
using IM.Easy.Entity.System;
using IM.Easy.Core.Utils;
using IM.Easy.SystemServices.Services;
using IM.Easy.Core.Attributes;
using Mapster;

namespace IM.Easy.Api.Controllers.System
{
    /// <summary>
    /// FileResourceController 控制器
    /// </summary>
    [Route("system/file")]
    public class FileResourceController : ControllerBase
    {
        private readonly IFileResourceService _service;
        private readonly IFolderService _folderService;
        private readonly IFileTypesService _fileTypesService;

        /// <summary>
        /// 构造函数，注入服务
        /// </summary>
        /// <param name="service">服务接口</param>
        public FileResourceController(IFileResourceService service, IFolderService folderService, IFileTypesService fileTypesService)
        {
            _service = service;
            _folderService = folderService;
            _fileTypesService = fileTypesService;
        }

        /// <summary>
        /// 根据ID获取FileResource对象
        /// </summary>
        /// <param name="id">对象的ID</param>
        /// <returns>返回指定的FileResource对象</returns>
        [Api(Name = "获取文件详情", Perm = "fileresource:info")]
        [HttpGet("{id}")]
        public FileResourceDto GetById([FromRoute] Guid id)
        {
            var result = _service.GetById(id);
            return result ?? throw new KeyNotFoundException($"未找到ID为 {id} 的FileResource对象。");
        }

        /// <summary>
        /// 上传文件并创建新的 FileResource 对象
        /// </summary>
        /// <param name="file">上传的文件，multipart/form-data 格式</param>
        /// <returns>返回创建后的 FileResource 对象</returns>
        [Api(Name = "上传文件", Perm = "fileresource:upload")]
        [HttpPost("upload")]
        public async Task<FileResourceDto> UploadFile([FromForm] FileUploadDto dto)
        {

            var file = dto.File;
            var folder = _folderService.GetById(dto.Folder);
            if (file == null)
            {
                ExceptionUtils.ThrowBusinessException("未上传文件");
            }

            if (folder == null) ExceptionUtils.ThrowBusinessException("未找到相关文件夹");

            var fileType = _fileTypesService.Recognize(file);
            if (!fileType.IsActive) ExceptionUtils.ThrowBusinessException("该类型文件被禁止上传");
            var path = await _service.LocalStorage(file);
            // 创建 FileResource 实体，根据上传的文件信息进行初始化
            var fileResource = new FileResource
            {
                FileName = file.FileName,
                Extension = Path.GetExtension(file.FileName),
                Mime = file.ContentType,
                FileSize = file.Length,
                FilePath = path,
                FolderId = folder.Id,
            };
            // 调用业务逻辑层进行持久化（例如保存到数据库）
            _service.Create(fileResource);
            var resource = GetById(fileResource.Id);
            return resource;
        }

        /// <summary>
        /// 批量删除FileResource对象
        /// </summary>
        /// <param name="ids">对象的IDS</param>
        [Api(Name = "删除文件", Perm = "fileresource:del")]
        [HttpDelete]
        public void Delete([FromBody] Guid[] ids)
        {
            var physicalPaths = _service.Delete(ids);
            _service.DeleteStorage([.. physicalPaths]);
        }

        /// <summary>
        /// 文件重命名
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPut("rename")]
        [Api(Name = "文件重命名", Perm = "fileresource:put")]
        public bool Rename([FromBody] ResourcesDto resource)
        {
            return _service.Rename(resource.Id.Value, resource.Name);
        }
    }
}
